<?php

namespace app\api\model;

use app\common\enums\StatusEnum;
use app\api\service\Token;
use app\common\controller\Send;
use app\api\model\OauthSession;
use think\Db;

class Phone extends \app\common\model\Phone
{
    
    use send;
    /**
     * 添加用户数据
     * @param $phone
     * @return mixed
     * @throws \think\Exception\DbException
     */
    public static function addOne($phone,$password)
    {
        $oauth = new Phone();
        $user = self::getByPhoneId($phone);
        if($user){
            return self::sendResult(141, [], '用户已注册');
        }else{
            $oauth->phone = $phone;
            $oauth->password = MD5($password);
            $oauth->share_key = self::shareKey();
            $oauth->status = StatusEnum::ENABLED;
            $oauth->save();
            $token = Token::generateToken();
            $uid   =  $oauth->id;
            cache($token, $uid, 8640000);
            self::login(true,$uid,$token);
            $refreshToken = Token::generateToken();
            cache($refreshToken,$uid,8640000 * 2);
            return self::sendResult(self::$okCode, [
                'uid' => $uid,
                'nickname' => '',
                'sex' => '',
                'province' => '',
                'city' => '',
                'country' => '',
                'headImg' => '',
                'shareKey' => $oauth->share_key,
                'autoplay' => '',
                'hasMobile' => 1,
                'token' => $token,
                'refreshToken' => $refreshToken,
            ]);
        }
        
        
    }
    

    /**
     * 添加用户 通过硬件id
     */
    public static function addOneByDevice($device)
    {
        $oauth = new Phone();
        $user = self::getByDevice($device);
        if($user){
            return self::sendResult(141, [], '用户已注册');
        }else{

            $oauth->device_info = $device;
            $oauth->money = 0;
            $oauth->share_key = self::shareKey();
            $oauth->status = StatusEnum::ENABLED;
            $oauth->save();
            $token = Token::generateToken();
            $uid   =  $oauth->id;

            cache($token, $uid, 8640000);
            self::login(true,$uid,$token);
            $refreshToken = Token::generateToken();
            cache($refreshToken,$uid,8640000 * 2);
            return self::sendResult(self::$okCode, [
                'uid' => $uid,
                'nickname' => '',
                'sex' => '',
                'province' => '',
                'city' => '',
                'country' => '',
                'headImg' => '',
                'shareKey' => $oauth->share_key,
                'autoplay' => '',
                'hasMobile' => 0,
                'token' => $token,
                'refreshToken' => $refreshToken,
            ]);
        }

    }
    /**
     * 更新设备信息
     */
    public static function updateDevice($res,$device)
    {

            $oauth = new Phone();
            $user = self::getByPhoneId($res['phone']);
            $data = [];
            $data['device_info'] = $device;
            $data['share_key'] = self::shareKey();
            $data['status']  = StatusEnum::ENABLED;
            Db::name('oauth')
            ->where('id', $res['uid'])
            ->data($data)
            ->update();
            $token = Token::generateToken();
            $uid   =  $user['id'];
            cache($token, $uid, 8640000);
            self::login(true,$uid,$token);
            $refreshToken = Token::generateToken();
            cache($refreshToken,$uid,8640000 * 2);
            return self::sendResult(self::$okCode, [
            'uid' => $uid,
            'nickname' => '',
            'sex' => '',
            'province' => '',
            'city' => '',
            'country' => '',
            'headImg' => '',
            'shareKey' => $user['share_key'],
            'autoplay' => '',
            'hasMobile' => 0,
            'token' => $token,
            'refreshToken' => $refreshToken,
        ]);
    }
    /**
     * 一键登录添加用户 通过手机
     */
    public static function addOnePhone($data = [])
    {
        $oauth = new Phone();
        $user = self::getByPhoneId($data['phone']);


        if($user){
            return self::sendResult(141, [], '用户已注册');
        }else{
            $oauth->phone = $data['phone'];
            $oauth->device_info = $data['device'];
            $oauth->money = 0;
            $oauth->share_key = self::shareKey();
            $oauth->status = StatusEnum::ENABLED;
            $oauth->save();
            $token = Token::generateToken();
            $uid   =  $oauth->id;
            cache($token, $uid, 8640000);
            self::login(true,$uid,$token);
            $refreshToken = Token::generateToken();
            cache($refreshToken,$uid,8640000 * 2);
            return self::sendResult(201, [
                'uid' => intval($uid),
                'phone' => $oauth->phone,
                'nickname' => '',
                'device_info'=>$oauth->device_info,
                'sex' => '',
                'province' => '',
                'city' => '',
                'country' => '',
                'headImg' => '',
                'shareKey' => $oauth->share_key,
                'autoplay' => '',
                'hasMobile' => 0,
                'token' => $token,
                'refreshToken' => $refreshToken,
            ],'注册成功');
        }


    }



    /**
     * 查询数据
     * @param $phone
     * @return mixed
     * @throws \think\Exception\DbException
     */
    public static function selectUserInfoByDeviceId($deviceId)
    {
        $oauth = new Phone();
        $user = self::getByDevice($deviceId);
        if($user){
            
            $token = Token::generateToken();
            $uid   =  $user['id'];
            cache($token, $uid, 8640000);
            self::login(true,$uid,$token);
            $refreshToken = Token::generateToken();
            cache($refreshToken,$uid,8640000 * 2);
            return self::sendResult(self::$okCode, [
                'uid' => $user['id'],
                'nickname' => $user['nickname'],
                'sex' => $user['sex'],
                'province' => $user['province'],
                'city' => $user['city'],
                'country' => $user['country'],
                'address' => $user['address'],
                'headImg' => $user['head_img'],
                'shareKey' => $user['share_key'],
                'autoplay' => $user['autoplay'],
                'phone' => $user['phone'],
                'hasMobile' => 0,
                'token' => $token,
                'refreshToken' => $refreshToken,
            ]);
            
        }else{
            return self::sendResult(141, [], '该用户未注册');
        }
    }

    /**
     * 查询数据
     * @param $phone
     * @return mixed
     * @throws \think\Exception\DbException
     */
    public static function selectUserInfoByPhone($phone,$device)
    {
        $oauth = new Phone();
        $user =  DB::name('oauth')->where('phone',$phone)->find();
//        $user = self::getByDevice($phone);
        $type = 0;
        if($user){
            if (empty($user['password'])) {
                $type = 1;
            }
            $token = Token::generateToken();
            $uid   =  $user['id'];
            cache($token, $uid, 8640000);
            self::login(true,$uid,$token);
            $refreshToken = Token::generateToken();
            cache($refreshToken,$uid,8640000 * 2);
            return self::sendResult(self::$okCode, [
                'uid' => intval($user['id']),
                'nickname' => $user['nickname'],
                'device_info' => $user['device_info'],
                'sex' => $user['sex'],
                'province' => $user['province'],
                'city' => $user['city'],
                'country' => $user['country'],
                'address' => $user['address'],
                'headImg' => $user['head_img'],
                'shareKey' => $user['share_key'],
                'autoplay' => $user['autoplay'],
                'phone' => $user['phone'],
                'hasMobile' => 0,
                'token' => $token,
                'type' => $type,
                'refreshToken' => $refreshToken,
            ]);

        }else{
            return self::sendResult(141, [], '未找到数据');
        }
    }


    /**
     * 查询数据
     * @param $phone
     * @return mixed
     * @throws \think\Exception\DbException
     */
    public static function selectUserInfoByAppleUser($appleUserId,$email)
    {
        $oauth = new Phone();
        $user = self::getByAppleUser($appleUserId);
        
        if(!$user){
            $oauth->email = $email;
            $oauth->apple_user_id = $appleUserId;
            $oauth->share_key = self::shareKey();
            $oauth->status = StatusEnum::ENABLED;
            $oauth->save();
        }
        $user = self::getByAppleUser($appleUserId);
        if($user['status'] == 0){
            return self::sendResult(108, [], '您的账号已被管理员冻结');
        }
        if($user){
            $token = Token::generateToken();
            $uid   =  $user['id'];
            cache($token, $uid, 8640000);
            self::login(true,$uid,$token);
            $refreshToken = Token::generateToken();
            cache($refreshToken,$uid,8640000 * 2);
            return self::sendResult(self::$okCode, [
                'uid' => $user['id'],
                'nickname' => $user['nickname'],
                'sex' => $user['sex'],
                'province' => $user['province'],
                'city' => $user['city'],
                'country' => $user['country'],
                'address' => $user['address'],
                'headImg' => $user['head_img'],
                'shareKey' => $user['share_key'],
                'autoplay' => $user['autoplay'],
                'phone' => $user['phone'],
                'hasMobile' => empty($user['phone']) ? 0 : 1,
                'token' => $token,
                'refreshToken' => $refreshToken,
            ]);
            
        }else{
            return self::sendResult(141, [], '该用户未注册');
        }
    }
    
    /**
     * 查询数据
     * @param $phone
     * @return mixed
     * @throws \think\Exception\DbException
     */
    public static function selectUserInfo($phone,$password)
    {
        $oauth = new Phone();
        $user = self::getByPhoneId($phone);
        if($user){
            if($user['password']!=MD5($password)){
                return self::sendResult(141, [], '密码不正确');
            }else if($user['status'] == 0){
                return self::sendResult(108, [], '您的账号已被管理员冻结');
            }else{
                $token = Token::generateToken();
                $uid   =  $user['id'];
                cache($token, $uid, 8640000);
                self::login(true,$uid,$token);
                $refreshToken = Token::generateToken();
                cache($refreshToken,$uid,8640000 * 2);
                return self::sendResult(self::$okCode, [
                    'uid' => $user['id'],
                    'nickname' => $user['nickname'],
                    'sex' => $user['sex'],
                    'province' => $user['province'],
                    'city' => $user['city'],
                    'country' => $user['country'],
                    'address' => $user['address'],
                    'headImg' => $user['head_img'],
                    'shareKey' => $user['share_key'],
                    'autoplay' => $user['autoplay'],
                    'phone' => $user['phone'],
                    'hasMobile' => 1,
                    'token' => $token,
                    'refreshToken' => $refreshToken,
                ]);
            }
        }else{
            return self::sendResult(141, [], '该用户未注册');
        }
    }
    /**
     * 指纹登录
     * @param $phone
     * @return mixed
     * @throws \think\Exception\DbException
     */
    public static function fingerprint($phone,$fingerprint)
    {
        $oauth = new Phone();
        $user = self::getByPhoneId($phone);
        if($user){
            $where  = [
                'fingerprint'=>$fingerprint,
                'oauth_id'=>$user['id']
            ];
            $fingerprint = DB::name('oauth_fingerprint')->where($where)->find();
            if(empty($fingerprint)){
                return self::sendResult(-2, [], '指纹不正确');
            }
            $token = Token::generateToken();
            $uid   =  $user['id'];
            cache($token, $uid, 8640000);
            self::login(true,$uid,$token);
            $refreshToken = Token::generateToken();
            cache($refreshToken,$uid,8640000 * 2);
            return self::sendResult(self::$okCode, [
                'uid' => $user['id'],
                'nickname' => $user['nickname'],
                'sex' => $user['sex'],
                'province' => $user['province'],
                'city' => $user['city'],
                'country' => $user['country'],
                'address' => $user['address'],
                'headImg' => $user['head_img'],
                'shareKey' => $user['share_key'],
                'autoplay' => $user['autoplay'],
                'phone' => $user['phone'],
                'hasMobile' => 1,
                'token' => $token,
                'refreshToken' => $refreshToken,
            ]);
        }else{
            return self::sendResult(141, [], '该用户未注册');
        }
    }


    /**
     * 验证码登录
     * @param $phone
     * @return mixed
     * @throws \think\Exception\DbException
     */
    public static function codeCheckUser($phone)
    {
        $oauth = new Phone();
        $user = self::getByPhoneId($phone);
        $type = 0;
        if($user){
            if($user['status'] == 0){
                return self::sendResult(108, [], '您的账号已被管理员冻结');
            }
            if (empty($user['password'])) {
                $type = 1;
            }
        }else{
            $oauth->phone = $phone;
            $oauth->share_key = self::shareKey();
            $oauth->status = StatusEnum::ENABLED;
            $oauth->save();
        }
        $token = Token::generateToken();
        $uid   =  $user['id']?$user['id']:$oauth->id;
        cache($token, $uid, 8640000);
        self::login(true,$uid,$token);
        $refreshToken = Token::generateToken();
        cache($refreshToken,$uid,8640000 * 2);
        return self::sendResult(self::$okCode, [
            'uid' => $uid,
            'nickname' => $user['nickname']?$user['nickname']:'',
            'sex' => $user['sex']?$user['sex']:0,
            'province' => $user['province']?$user['province']:'',
            'city' => $user['city']?$user['city']:"",
            'country' => $user['country']?$user['country']:'',
            'address' => $user['address']?$user['address']:'',
            'headImg' => $user['head_img']?$user['head_img']:"",
            'shareKey' => $user['share_key']?$user['share_key']:$oauth->share_key,
            'autoplay' => $user['autoplay']?$user['autoplay']:0,
            'phone' => $user['phone']?$user['phone']:$phone,
            'hasMobile' => 1,
            'type' => $type,
            'token' => $token,
            'refreshToken' => $refreshToken,
        ]);
        
    }

    /**
     * 根据phone更新一条数据
     * @param $openid
     * @param $data
     * @return array
     * @throws \think\Exception\DbException
     */
    public static function updateOne($openid, $data)
    {
        $user = self::getByOpenId($openid);
        if (empty($user)) {
            $user = new Oauth;
            $user->openid = $openid;
            $user->share_key = self::shareKey();
            $user->status = StatusEnum::ENABLED;
            $user->autoplay = self::AUTOPLAY;
        }
        $user->unionid = isset($data['unionid']) ? $data['unionid'] : '';
        $user->nickname = $data['nickname'];
        $user->sex = $data['sex'];
        $user->province = $data['province'];
        $user->city = $data['city'];
        $user->country = $data['country'];
        $user->head_img = $data['head_img'];
        return $user->save() ? $user : [];
    }

    /**
     * 根据openid更新手机号码
     * @param $openid
     * @param $data
     * @return boolean
     * @throws \think\Exception\DbException
     */
    public static function updatePhone($openid, $data)
    {
        $user = self::getByOpenId($openid);
        if ($user) {
            $user->phone = $data['phone'];
            $user->pure_phone = $data['pure_phone'];
            return $user->save() ? true : false;
        }
        return false;
    }

    /**
     * 编辑个性签名
     * @param $oauthId
     * @param $content
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function signature($oauthId, $content)
    {
        $user = self::getOne($oauthId);
        if ($user) {
            $user->signature = $content;
            return $user->save() ? true : false;
        }
        return false;
    }

    /**
     * 编辑是否自动播放
     * @param $oauthId
     * @param $autoplay
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function autoplay($oauthId, $autoplay)
    {
        $user = self::getOne($oauthId);
        if ($user) {
            $user->autoplay = $autoplay;
            return $user->save() ? true : false;
        }
        return false;
    }

    /**
     * id随机key
     * @param int $length 长度
     * @return string
     * @throws \think\Exception\DbException
     */
    private static function shareKey($length = 10)
    {
        $key = rand_char($length);
        $next = true;
        while ($next) {
            $model = Oauth::where(['share_key' => $key])->find();
            if (empty($model)) {
                $next = false;
            } else {
                $key = rand_char($length);
            }
        }
        return $key;
    }
    
    
    /**
     * 忘记密码
     * @param $phone
     * @return mixed
     * @throws \think\Exception\DbException
     */
    public static function forgetPwd($phone,$password)
    {
        $oauth = new Phone();
        $user = self::getByPhoneId($phone);
        if(!$user){
            return self::sendResult(141, [], '用户未注册');
        }else{
            $user->id = $user['id'];
            $user->phone = $phone;
            $user->password = MD5($password);
            $user->share_key = self::shareKey();
            $user->status = StatusEnum::ENABLED;
            $user->save();
            $token = Token::generateToken();
            $uid   =  $user['id'];
            cache($token, $uid, 8640000);
            self::login(true,$uid,$token);
            $refreshToken = Token::generateToken();
            cache($refreshToken,$uid,8640000 * 2);
            return self::sendResult(self::$okCode, [
                'uid' => $uid,
                'nickname' => $user['nickname'],
                'sex' => $user['sex'],
                'province' => $user['province'],
                'city' => $user['city'],
                'country' => $user['country'],
                'address' => $user['address'],
                'headImg' => $user['head_img'],
                'shareKey' => $user->share_key,
                'autoplay' => $user['autoplay'],
                'hasMobile' => $user['phone']?1:0,
                'token' => $token,
                'refreshToken' => $refreshToken,
            ]);
        }
    
    
    }
    
    /**
     * 登录添加缓存
     */
    public static function login($keepLogin,$userId,$token){
        $liveSeconds = $keepLogin ? 3 * 365 * 24 * 60 * 60 : 120 * 60;
        $expireAt = time() + $liveSeconds;
        $source = checkMiniprogram() ? 2:1;
        $sessionList = OauthSession::getSessionsByUserIdAndSource($userId,$source);
        if(!empty($sessionList)){
            foreach ($sessionList as $key => $value) {
                OauthSession::deleteSession($userId,$value['id']);
                cache($value['token'], null, 1);
            }
            
        }

        OauthSession::addSession($token,$userId,$expireAt);
    }
}